package nancal.mp.service.jenkins.ops

import nancal.mp.db.mongo.extend.getAppDeploySetting
import nancal.mp.db.mongo.mor
import nancal.mp.service.jenkins.JenkinsExportModel
import nancal.mp.service.jenkins.publish.FileContent
import nancal.mp.service.jenkins.publish.FunctionContent
import nbcp.base.comm.config
import nbcp.base.extend.AsString
import nbcp.base.extend.Skip
import nbcp.base.extend.must
import nbcp.base.utils.WebUtil

fun JenkinsExportModel.getK8sOpsFiles(): List<FileContent> {
    var upload_minio = FileContent("upload_minio.sh", FunctionContent("upload_minio", """
host=${
        WebUtil.getHostUrlWithoutHttp(
            config.getConfig("app.upload.minio.api-host")
                .must()
                .elseThrow { "找不到配置项 app.upload.minio.api-host" })
            .trim('/')
    }

bucket=${config.getConfig("app.upload.minio.bucket").AsString("mpm")}
file=＄1
s3_key=${
        config.getConfig("app.upload.minio.key")
            .must()
            .elseThrow { "找不到配置项 app.upload.minio.key" }
    }
s3_secret=${
        config.getConfig("app.upload.minio.secret")
            .must()
            .elseThrow { "找不到配置项 app.upload.minio.secret" }
    }


resource="/＄bucket/＄file"
content_type="application/octet-stream"
date=`date -R`
_signature="PUT\n\n＄content_type\n＄date\n＄resource"
signature=`echo -en ＄_signature | openssl sha1 -hmac ＄s3_secret -binary | base64`


echo 上传minio文件: ＄file --> http://＄host＄resource

curl -v -# -X  PUT -T "＄file" \
          -H "Host: ＄host" \
          -H "Date: ＄date" \
          -H "Content-Type: ＄content_type" \
          -H "Authorization: AWS ＄s3_key:＄signature" \
          http://＄host＄resource

""").toString().replace('＄', '$'));


    var f_docker_save = FileContent(
        "docker_save.sh", FunctionContent(
            "docker_save", """
name=＄1
image_name_version=＄2


echo ${mor.dev.appDeploySetting.getAppDeploySetting(this.targetEnv).sudo} docker pull ＄image_name_version
${mor.dev.appDeploySetting.getAppDeploySetting(this.targetEnv).sudo} docker pull ＄image_name_version

echo ${mor.dev.appDeploySetting.getAppDeploySetting(this.targetEnv).sudo} docker save -o k8s-ops/docker/＄name.tar ＄image_name_version
${mor.dev.appDeploySetting.getAppDeploySetting(this.targetEnv).sudo} docker save -o k8s-ops/docker/＄name.tar ＄image_name_version

"""
        ).toString().replace('＄', '$')
    )


    var f_mysql_dump = FileContent("mysql_dump.sh", FunctionContent("mysql_dump", """
host=＄1
port=＄2
user=＄3
password=＄4
db=＄5


# 修复 63 由于 Jenkins 安装在 docker，导致 挂载目录和 jenkins 目录不一致的问题。

${mor.dev.appDeploySetting.getAppDeploySetting(this.targetEnv).sudo}  docker run -i --rm  --privileged=true -v /opt＄{PWD:4}/k8s-ops/mysql:/mysql-bak  ${
        config.getConfig("app.mysql-docker").AsString{mor.dev.appDeploySetting.getAppDeploySetting().harborServer.getHarborToolImagePrefix() +"mariadb:10.7.8"}
    }  /bin/bash  -c "mysqldump  --host=＄host  --port=＄port --user=＄user --password=＄password  --routines  --databases ＄db > /mysql-bak/＄db.sql && ls /mysql-bak"

sudo chmod a+rw -R ./

""").toString().replace('＄', '$'))


    var f_mysql_restore = FileContent("k8s-ops/mysql_restore.sh", FunctionContent("mysql_restore", """
host=＄1
port=＄2
user=＄3
password=＄4
file=＄5

if [ "＄file" == "" ]; then
    echo "mysql_restore 参数错误"
    exit 1
fi

if [ "＄{file:0-4:4}" != ".sql" ]; then
    echo "mysql_restore 参数错误, 数据库文件必须以 .sql 结尾"
    exit 1
fi

db="＄{file:0-4:4}"

${mor.dev.appDeploySetting.getAppDeploySetting(this.targetEnv).sudo}  docker run -i --rm  --privileged=true -v ＄PWD/k8s-ops/mysql:/mysql-bak  ＄harbor_addr/tools/mariadb:10.7.8  /bin/bash  -c "ls /mysql-bak  &&  mysql --host=＄host  --port=＄port --user=＄user --password=＄password  --databases ＄db <  /mysql-bak/＄db.sql  "

sudo chmod a+rw -R ./

""").toString().replace('＄', '$'))


    var f_mongo_dump = FileContent("mongo_dump.sh", FunctionContent("mongo_dump", """
host=＄1
port=＄2
user=＄3
password=＄4
db=＄5


# 修复 63 由于 Jenkins 安装在 docker，导致 挂载目录和 jenkins 目录不一致的问题。

${mor.dev.appDeploySetting.getAppDeploySetting(this.targetEnv).sudo}  docker run -i --rm  --privileged=true -v /opt＄{PWD:4}/k8s-ops/mongo:/mongo-bak  ${
        config.getConfig("app.mongo-docker").AsString {mor.dev.appDeploySetting.getAppDeploySetting().harborServer.getHarborToolImagePrefix() +"mongo:5.0.3"}
    }  /bin/bash  -c "mongodump  --forceTableScan --host=＄host --port=＄port --db=＄db --username=＄user --password=＄password  --gzip  --authenticationDatabase=admin --out=/mongo-bak && ls /mongo-bak"

sudo chmod a+rw -R ./

""").toString().replace('＄', '$'))


    var f_mongo_restore =
        FileContent(
            "k8s-ops/mongo_restore.sh", FunctionContent(
                "mongo_restore", """
host=＄1
port=＄2
user=＄3
password=＄4

docker run -i --rm  --privileged=true -v ＄PWD/k8s-ops/mongo:/mongo-bak  ＄harbor_addr/tools/mongo:5.0.3  /bin/bash  -c "ls /mongo-bak  && mongorestore  --host=＄host --port=＄port  --username=＄user --password=＄password  --gzip --drop  --authenticationDatabase admin  /mongo-bak "

"""
            ).toString().replace('＄', '$')
        )

    var f_docker_push = FileContent(
        "k8s-ops/docker_push.sh", FunctionContent(
            "docker_push", """
old=＄1
new=＄2

echo docker tag ＄old  ＄new
docker tag ＄old  ＄new

echo docker push ＄new
docker push ＄new

"""
        ).toString().replace('＄', '$')
    );

    var config = FileContent(
        "config.sh", """

# ========== 需要手工修改以下内容 ==========
# kuboard 镜像 第一部分
export harbor_addr=HarborIpPort


export mongo_ip=
# kuboard 中 mongo 服务的节点端口
export mongo_port=27017
export mongo_user=root
export mongo_pwd=


export mysql_ip=
# kuboard 中 mysql 服务的节点端口
export mysql_port=3306
export mysql_user=root
export mysql_pwd=

# ==========  修改结束  ==========

"""
    );

    var install = FileContent(
        "install.sh", """
source config.sh

echo 合并文件  cat k8s-ops-* > k8s-ops.tar.gz
cat k8s-ops-* > k8s-ops.tar.gz

echo 解压缩文件 tar -xzvf  k8s-ops.tar.gz 
tar -xzvf  k8s-ops.tar.gz 


echo 当前目录＄PWD
ls

echo 加载 ./k8s-ops/docker 下的 docker 镜像

for file in `ls ./k8s-ops/docker`
do
    echo docker load -i  k8s-ops/docker/＄file
    docker load -i  k8s-ops/docker/＄file
done


echo push  ${
            k8sServiceImages.map { it.fullImageVersion }.joinToString(",")
        }  ----> ＄harbor_addr
        
source k8s-ops/docker_push.sh

${
            k8sServiceImages.map {
                return@map "docker_push ${it.fullImageVersion}  ＄harbor_addr/${
                    it.fullImageVersion.split(
                        "/"
                    ).Skip(1).joinToString("/")
                }"
            }.joinToString("\n")
        }


echo 推送完成！ 请在 kuboard 中手动更新镜像版本！


if [ "＄(ls -A k8s-ops/mongo)" ]; then
    echo 恢复数据库 k8s-ops/mongo
    ls
    source k8s-ops/mongo_restore.sh
    echo mongo_restore ＄mongo_ip ＄mongo_port  ＄mongo_user  ＄mongo_pwd
    mongo_restore ＄mongo_ip ＄mongo_port  ＄mongo_user  ＄mongo_pwd 
else
    echo "mongo数据库目录为空，跳过恢复mongo!!!"
fi


if [ "＄(ls -A k8s-ops/mysql)" ]; then
    echo 恢复数据库 k8s-ops/mysql
    ls
    source k8s-ops/mysql_restore.sh
    
    for file in `ls ./k8s-ops/mysql`
    do
        echo mysql_restore ＄mysql_ip ＄mysql_port  ＄mysql_user  ＄mysql_pwd    ＄file
        mysql_restore ＄mysql_ip ＄mysql_port  ＄mysql_user  ＄mysql_pwd    ＄file
    done

else
    echo "mysql数据库目录为空，跳过恢复mysql!!!"
fi


"""
            .replace('＄', '$')
    );



    return listOf(
        config,
        install,
        f_mongo_dump, f_mongo_restore,
        f_mysql_dump, f_mysql_restore,
        f_docker_push, f_docker_save
    );
}
